package com.only4play.practice.common.model;

import com.only4play.codegen.support.constants.BaseEnum;
import com.only4play.practice.common.BizCodeEnum;
import com.only4play.practice.common.exception.BizException;
import lombok.Data;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.Objects;

@Data
public class RespWrapper<T> implements Serializable {


    /**
     * 错误码
     *
     */
    private Integer code;

    /**
     * 错误提示，用户可阅读
     *
     */
    private String msg;

    /**
     * 返回数据
     */
    private T data;

    public RespWrapper() {
    }

    public RespWrapper(T data) {
        this.data = data;
    }

    /**
     * 将传入的 result 对象，转换成另外一个泛型结果的对象
     *
     * 因为 A 方法返回的 CommonResult 对象，不满足调用其的 B 方法的返回，所以需要进行转换。
     *
     * @param result 传入的 result 对象
     * @param <T>    返回的泛型
     * @return 新的 CommonResult 对象
     */
    public static <T> RespWrapper<T> error(RespWrapper<?> result) {
        return error(result.getCode(), result.getMsg());
    }
    public static <T> RespWrapper<T> error(Integer code, String message) {
        Assert.isTrue(!(BizCodeEnum.CODE_SUCCESS.getCode().equals(code)), "code 必须是错误的！");
        RespWrapper<T> result = new RespWrapper<>();
        result.code = code;
        result.msg = message;
        return result;
    }

    public static <T extends Enum<T> & BaseEnum<T>> RespWrapper<T> error(BaseEnum<T> baseEnum) {
        return error(baseEnum.getCode(), baseEnum.getName());
    }

    public static <T> RespWrapper<T> error(BizException bizException) {
        return error(bizException.getCode(), bizException.getMessage());
    }

    public static <T> RespWrapper<T> success(T data) {
        RespWrapper<T> result = new RespWrapper<>();
        result.code = BizCodeEnum.CODE_SUCCESS.getCode();
        result.data = data;
        result.msg = "ok";
        return result;
    }

    public boolean isSuccess(Integer code) {
        return Objects.equals(code, BizCodeEnum.CODE_SUCCESS.getCode());
    }
    public RespWrapper(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}